/**
 *用户 、角色权限设置控件
 */
define(function(require ,exports ,module){
    var Modal = require("commons/modal");
    var common = require("commons/common");

    /**
     * 初始化权限设置对象
     * @param userid 用户id或者角色id
     * @param type
     * @constructor
     */
    var Permission = function(userid,type){
        this.id = userid ; //id
        this.type = type ||"u" ; //u ->user r->role 默认用户

        this.modal=null ;
        this.sdmsTree = null ;//后台管理树
        this.sysTree = null ;
        this.sysGrid = null ;
        this.dataTree = null ;
        this.dataGrid = null ;
        this.operParId ="";//当前操作的权限树节点id

        this._majorConfig =null;//专业和行业对应关系

         /**
         * 配置项
         */
         this.config = {
            id:"set_auth_modal", //唯一
            tabs :{
                sys:"sys-auth",
                data:"data-auth"
            },
            className:{
                 role :"setroleauth",
                 user :"setuserauth"
            },
            modal:{
                className:"setauthModal",
                size:"md"
            },
            grid :{
                "sys-grid":"sys-grid",
                "data-grid":"data-grid"
            },
            tree:{
                "sys-tree":"sys-tree",
                "data-tree":"data-tree",
                "sdms-tree":"sdms-tree"
            }
        };

        /**
         * 树节点响应事件
         */
        this.actions  = function(){
            var that = this ;
            return {
                "sys":{
                    "onClick":function(id){
                        that.operParId = id ;
                        var gridCon = $("#"+that.config.grid["sys-grid"]) ;
                        var treeCon = $("#"+that.config.tree["sdms-tree"]);
                        gridCon.addClass("hide");
                        treeCon.addClass("hide");
                        if(id == "sys"){
                            that.sysGrid&&that.sysGrid.clearAll(false);
                            gridCon.removeClass("hide");
                            return ;
                        }
                        SGIS.API.get("/powers/"+that.id+"/tree/"+id).data({
                                type:that.type
                            })
                            .data(JSON.stringify(that._majorConfig))
                            .json(function(re){
                            //节点6是后台管理权限
                            if(id == "6_sys"){
                                treeCon.removeClass("hide");
                                that.sdmsTree&&that.sdmsTree.destructor();
                                that.sdmsTree = null ;
                                that.sdmsTree = SGIS.Tree.createCheckableTree(that.config.tree["sdms-tree"], re[0],
                                    that.actions().sdms, null);

                            }else{
                                gridCon.removeClass("hide");
                                that.addPowerGrid(re,that.sysGrid);
                            }
                        });
                    }
                },
                "sdms":{
                    "onCheck":function(id,status){
//                        alert(id)
                        return true ;
                    },
                    "onSelect":function(id){
//                        alert(id)
                    },
                    "onClick":function(id){
                        that.sdmsTree.setCheck(id,!that.sdmsTree.isItemChecked(id));
                    }

                },
                "data":{
                    "onClick":function(id){
                        that.operParId = id ;
//                        if(id=="macro"){
//                            that.dataGrid&&that.dataGrid.clearAll(false);
//                            return ;
//                        }
                        SGIS.API.get("/powers/"+that.id+"/tree/"+id).data({
                            type:that.type
                        })
                            .data(JSON.stringify(that._majorConfig))
                            .json(function(re){
                            var obj = [];
                            if(!re)return;
                            for(var i=0,leng=re.length; i<leng; i++) {
                                var id = re[i].id;
                                if (id == "179" || id == "4" || id == "178" || id == "181" || id == "180" || that.operParId!="micro") {
                                    obj.push(re[i]);
                                }
                            }
                            that.addPowerGrid(obj,that.dataGrid);
                        });
                    }
                }
            };
        };

        /**打开加载子节点*/
        this.lazyLoad = function () {
            var that = this ;
            return function(obj, id){
                that.onpenStartTree(obj, id);
            };
        };

        //初始化页面
        this.init = function(){
            var that = this ;
            var tablist ='<ul class="nav nav-pills nav-justified" role="tablist">'
                +'<li role="presentation" class="active"><a href="#sys-auth" role="tab" data-toggle="tab">系统权限</a></li>'
                +'<li role="presentation"><a href="#data-auth" role="tab" data-toggle="tab">数据权限</a></li>  </ul>';
            var tabcontent = '<div class="tab-content">'
                +'<div class="tab-pane active" id="sys-auth">'
                +'<div class="row">'
                +'<div class="col-md-4">'
                +'<div id="sys-tree" ></div>'
                +'</div>'
                +' <div class="col-md-8">'
                +'<div id="sdms-tree" class="hide"></div>'
                +'<div id="sys-grid" class="grid-container"></div>'
                +'</div>'
                +'</div>'
                +'</div>'
                +'<div class="tab-pane" id="data-auth">'
                +'<div class="row">'
                +'  <div class="col-md-4">'
                +'   <div id="data-tree"></div>'
                +' </div>'
                +'<div class="col-md-8">'
                +'  <div id="data-grid" class="grid-container"></div>'
                +'</div>'
                +'</div>'
                +'</div>'
                +'</div>';
            var footer ='' +
                '<button type="button" class="btn btn-link" id="power-selall-btn">全选</button>'
                +'<button type="button" class="btn btn-link" id="power-selother-btn">反选</button>'
                +'<button type="button" class="btn btn-default"  data-toggle="#{{id}}" data-dismiss="modal">取消</button>'
                +'<button type="button" class="btn btn-primary" id="setAuth-ok-btn">确认</button>';
            var body = tablist+tabcontent ;
            body = body.replace("{{id}}",that.config.id);

            var title =type =="u"?"设置用户权限":"设置角色权限";
            var modal = new Modal(that.config.id,title,{"size":"lg"});
            modal.setMbody($(body));
            modal.setMfooter($(footer));
            that.modal = modal ;

            var tc = that.config.tree ;
            var gc = that.config.grid;
            modal.find("#"+tc["sys-tree"]
                +",#"+tc["sdms-tree"]
                +",#"+tc["data-tree"]
                ).css({
                    'position': 'relative',
                    'top': '15px',
                    'height': '330px',
                    'width': '100%'
            });
            modal.find(
                    "#"+gc["sys-grid"]
                    +",#"+gc["data-grid"]
                ).css({
                    'position': 'relative',
                    'top': '0px',
                    'height': '330px',
                    'width': '100%'
            });

            var gc = that.config.grid
            that.sysGrid&&that.sysGrid.destructor();
            that.sysGrid =  SGIS.Grid.create(gc["sys-grid"]);
            that.sysGrid.setHeader("选择,序号,权限名称");
            that.sysGrid.setInitWidths("100,100,150");
            that.sysGrid.setColSorting("str,int,str");
            that.sysGrid.init();

            that.dataGrid&&that.dataGrid.destructor();
            that.dataGrid =  SGIS.Grid.create(gc["data-grid"]);
            that.dataGrid.setHeader("选择,序号,权限名称");
            that.dataGrid.setInitWidths("100,100,150");
            that.dataGrid.setColSorting("str,int,str");
            that.dataGrid.init();

            function XML2String(xmlObject) {
                // for IE
                if (window.ActiveXObject) {
                    return xmlObject.xml;
                }
                // for other browsers
                else {
                    return (new XMLSerializer()).serializeToString(xmlObject);
                }
            }

            $.getJSON(require.resolve('commons/major.industry.config.json'), function (re) {
                that._majorConfig = eval(re);
                //获取权限树
                SGIS.API.get("/powers/"+that.id+"/tree")
                    .data(JSON.stringify(that._majorConfig||[]))
                    .json(function(d){

                    that.sysTree && that.sysTree.destructor();
                    that.sysTree = SGIS.Tree.create(tc["sys-tree"], d.sys, that.actions().sys, null);

                    /** 面向一般用户限制 start */
                    var $micro = $(d.data).find("#micro");
                    var strdata = "<?xml version='1.0' encoding='utf-8'?><tree id='tree0'>"+
                        "<item id='micro' text='基层数据'  open='1' nocheckbox='1'>"+
                        "<item id='179_micro' text='全部单位（默认）'  nocheckbox='1'>"+
                            "</item><item id='4_micro' text='四上单位'  nocheckbox='1'>"+
                            "</item><item id='178_micro' text='四下单位'  nocheckbox='1'>"+
                            "</item><item id='181_micro' text='重点跟踪企业'  nocheckbox='1'>"+
                            "</item><item id='180_micro' text='个体单位'  nocheckbox='1'>"+
                            "</item></item></tree>";
                    if(!$micro || $micro.length<1) strdata = d.data;//非基层数据
                    /** 面向一般用户限制 end */

                    that.dataTree && that.dataTree.destructor();
                    that.dataTree = SGIS.Tree.create(tc["data-tree"], strdata, that.actions().data, that.lazyLoad());
                });
            });

            //设置权限
            $("#setAuth-ok-btn").click(function(){
                var parid = that.operParId ;
                var split = parid.split("_");
                var len = split.length ;
                if(parid ==""){
                    SGIS.UI.alert("请先选择权限");
                    return ;
                }
                var selIdsArr = new Array();
                if(split[len-1] =="sys"){
                    var  pcataid = parseInt(split[0]);
                    //后台管理数
                    if(pcataid == 6){
                         var arr = that.sdmsTree.getAllCheckedBranches().split(",");
                        for(var i=0 ; i<arr.length ;i++){
//                            if(that.sdmsTree.hasChildren(arr[i])){
//                                continue ;
//                            }
                            selIdsArr.push(arr[i]);
                        }
                    }else{
                        $("#sys-grid .isChecked:checked").each(function(){
                            selIdsArr.push($(this).attr("rowid"))
                        });
                    }
                }
                else {
                    $("#data-grid .isChecked:checked").each(function(){
                        selIdsArr.push($(this).attr("rowid"))
                    });
                }
//                if(selIdsArr.length<1){
//                    SGIS.UI.alert("请先选择权限");
//                    return ;
//                }
                var url = "/powers/{userid}/tree/{selId}/setpowers";
                url = url.replace("{userid}",that.id);
                url = url.replace("{selId}",that.operParId);
                SGIS.API.post(url).data({
                    type:that.type
                }).data(JSON.stringify(selIdsArr))
                   .json(function(re){
                    if(re.status){
                        SGIS.UI.alert("设置成功");
                    }else{
                        SGIS.UI.alert("设置失败");
                    }
                    //重新刷新表格
                    if(that.operParId.indexOf("sys")!=-1){
                        that.sysTree.selectItem(that.operParId,true);
                    }else{
                        that.dataTree.selectItem(that.operParId,true);
                    }
                });
            });

            //全选
            modal.find("#power-selall-btn").click(function(){
                var type = that.operParId ;
                if(type == ""||type =="sys"){
                    return ;
                }
                if(type.indexOf("sys")!=-1){
                    var parid = parseInt(type.split("_")[0]);
                    if( parid == 6){
                        var arr = that.sdmsTree.getAllChildless().split(",");
                        for(var i=0 ; i<arr.length ;i++){
                            var status = that.sdmsTree.isItemChecked(arr[i]);
                            if(!status){
                                that.sdmsTree.setCheck(arr[i],!status);
                            }
                        }
                    }else{
                        $("#sys-grid .isChecked").each(function(i,o){
                            if(!o.checked){
                                o.checked = true ;
                            }
                        });
                    }
                }else{
                    $("#data-grid .isChecked").each(function(i,o){
                        if(!o.checked){
                            o.checked = true ;
                        }
                    });
                }
            });
            //反选
            modal.find("#power-selother-btn").click(function(){
                var type = that.operParId ;
                if(type == ""||type =="sys"){
                    return ;
                }
                if(type.indexOf("sys")!=-1){
                    var parid = parseInt(type.split("_")[0]);
                    if( parid == 6){
                        var arr = that.sdmsTree.getAllChildless().split(",");
                        for(var i=0 ; i<arr.length ;i++){
                            var status = that.sdmsTree.isItemChecked(arr[i]);
                            that.sdmsTree.setCheck(arr[i],!status);
                        }
                    }else{
                        $("#sys-grid .isChecked").each(function(i,o){
                            o.checked = !o.checked ;
                    });
                    }
                }else{
                    $("#data-grid .isChecked").each(function(i,o){
                        o.checked = !o.checked ;
                    });
                }
            });

        };
        this.init();


    };

    Permission.prototype ={
        addPowerGrid :function(re,grid){
            var id ="id";
            var fields = ["name","status"] ;
            var d = common.jsonToGridData(re,id,fields,true);
            d =this.handleGridData(d);
            grid&grid.clearAll(false);
            grid&&grid.parse(d,"json");
        },
        handleGridData : function(d){
            var checkboxTempl ="<input  type='checkbox'  rowid='{{rowid}}' class='isChecked' {{checked}}>";
            var rows = d.rows ;
            for(var i = 0 ; i< rows.length ; i++){
                var len = rows[i].data.length ;
                var status = rows[i].data[len-1];
                var checkbox = checkboxTempl;
                if(status == "checked"){
                    checkbox = checkbox.replace("{{checked}}","checked");
                }else{
                    checkbox = checkbox.replace("{{checked}}","");
                }
                delete  rows[i].data[len-1] ;
                rows[i].data = [checkbox.replace("{{rowid}}",rows[i].id)].concat(rows[i].data);
            };
            return {rows:rows};
        },
        /**
         * 判断是否还有load节点
         * @param obj
         * @param id
         * @returns {boolean}
         */
         hasTempNode : function (obj, id) {
            var tempnode = obj.getAllSubItems(id).indexOf("load");
            if (tempnode == 0) {
                return true;//未加载
            }
        },
        /**
         * 打开添加子节点
         * @param id
         */
         addTreeNode :function(id) {
            var that = this ;
            SGIS.API.get("/powers/"+that.id+"/tree/"+"?/macro", id)
                .json(function (param) {
                    if (param != null && param != "") {
                        that.dataTree.loadXMLString(param);
                    }
            });
        },

        //打开加载子节点
        onpenStartTree : function (obj, id) {
            //基层节点一次性加载完了
            if(id.indexOf("micro") != -1
                ||id.indexOf("macro") != -1){ return ;}
            if (this.hasTempNode(obj, id)) {//未加载过
                obj.deleteChildItems(id);//删除子节点
                this.addTreeNode(id);//查询并加载子节点
            }
        },
        /**
         * 切换用户重新加载
         */
        switchId :function(newId){
            this.sysGrid&&this.sysGrid.clearAll();
            this.sdmsTree&&this.sdmsTree.destructor();
            this.sdmsTree = null;
            this.dataGrid&&this.dataGrid.clearAll();
            this.id = newId ;
        },
        /**
         * 设置权限
         */
        setAuth :function(){

        },
        /**
         * 显示设置面板
         */
        show :function(){
            this.modal.show();
        },
        /**
         * 隐藏设置面板
         */
        hide : function(){
            this.modal.hide();
        },
        /**
         * 销毁面板
         */
        dispose:function(){
            this.modal.dispose();
        }

    };

    return Permission ;
});